package com.seal.yoyoshop.adminweb;

import com.seal.yoyoshop.bin.Goods;
import com.seal.yoyoshop.bin.Type;
import com.seal.yoyoshop.service.GoodsService;
import com.seal.yoyoshop.service.TypeService;
import com.seal.yoyoshop.service.impl.GoodsServiceImpl;
import com.seal.yoyoshop.service.impl.TypeServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.UUID;

@MultipartConfig
@WebServlet(name = "GoodsEditServlet", value = "/admin/goodsEdit")
public class GoodsEditServlet extends HttpServlet {

    private TypeService typeService = new TypeServiceImpl();
    private GoodsService goodsService = new GoodsServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("flag",3);
        List<Type> typeList = typeService.getTypeList();
        request.setAttribute("typeList",typeList);

        String goodsIdstr = request.getParameter("id");
        int goodsId = Integer.parseInt(goodsIdstr);
        String statusstr = request.getParameter("status");
        int status = Integer.parseInt(statusstr);
        Goods goods = goodsService.getGoodById(goodsId);
        request.setAttribute("goods",goods);

        request.setAttribute("status",status);

        request.getRequestDispatcher("/admin/goods_edit.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("flag",3);
        List<Type> typeList = typeService.getTypeList();
        request.setAttribute("typeList",typeList);

        String goodsIdstr = getPartValue(request.getPart("id"));
        int goodsId = Integer.parseInt(goodsIdstr);
        String topTypestr = getPartValue(request.getPart("topType"));
        int topType = Integer.parseInt(topTypestr);
        Goods goods = goodsService.getGoodById(goodsId);

        String name = getPartValue(request.getPart("name"));
        if(name.length() > 40) {
            request.setAttribute("msg","添加失败，商品名超过40字");

            request.setAttribute("goods",goods);
            request.setAttribute("status",topType);

            request.getRequestDispatcher("/admin/goods_edit.jsp").forward(request,response);
            return;
        }
        String pricestr = getPartValue(request.getPart("price"));
        double price = 0;
        try {
            price = Double.parseDouble(pricestr);
        }catch (Exception e) {
            request.setAttribute("msg","添加失败，商品价格必须是整数或小数");

            request.setAttribute("goods",goods);
            request.setAttribute("status",topType);

            request.getRequestDispatcher("/admin/goods_edit.jsp").forward(request,response);
            return;
        }

        String intro = getPartValue(request.getPart("intro"));
        if(intro.length() > 255) {
            request.setAttribute("msg","添加失败，商品介绍过长");

            request.setAttribute("goods",goods);
            request.setAttribute("status",topType);

            request.getRequestDispatcher("/admin/goods_edit.jsp").forward(request,response);
            return;
        }
        String stockstr = getPartValue(request.getPart("stock"));
        int stock = 0;
        try {
            stock = Integer.parseInt(stockstr);
        }catch (Exception e) {
            request.setAttribute("msg","添加失败，商品库存必须是整数");

            request.setAttribute("goods",goods);
            request.setAttribute("status",topType);

            request.getRequestDispatcher("/admin/goods_edit.jsp").forward(request,response);
            return;
        }
        String typeIdstr = getPartValue(request.getPart("typeId"));
        int typeId = Integer.parseInt(typeIdstr);

        goods.setName(name);
        goods.setPrice(price);
        goods.setIntro(intro);
        goods.setTypeId(typeId);

        String cover = getImage(request.getPart("cover"));
        if(cover != null){
            goods.setCover(cover);
        }
        String img1 = getImage(request.getPart("image1"));
        if(img1 != null){
            goods.setImage1(img1);
        }
        String img2 = getImage(request.getPart("image2"));
        if(img2 != null){
            goods.setImage2(img2);
        }
//        更新商品信息
        boolean isSuccess = goodsService.updateGoods(goods);
        response.sendRedirect("goodsList?status=" + topType + "&page=1&size=16");

    }
    public String getImage(Part part) {
        String userFileName = part.getSubmittedFileName();
        String path = null;
        if(userFileName.endsWith(".jpg") || userFileName.endsWith(".png")){
//        获取文件名最后一个.
            int lastDot = userFileName.lastIndexOf(".");
//        获取后缀
            String suffix = userFileName.substring(lastDot);
//        uuid
            UUID uuid = UUID.randomUUID();
            String uuidstr = uuid.toString();
            String fileName = uuidstr + suffix;
//        System.out.println(fileName);
            String picturePath = this.getServletContext().getRealPath("/picture");
//        System.out.println(picturePath);
            String savePath = picturePath + "/" + fileName;
            try {
                part.write(savePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
//        存数据库地址
            path = "picture/" + fileName;
        }
        return path;
    }

    public String getPartValue(Part part) {
        String value = null;
//        JDK1.7之后，针对需要关闭的内容（流，链接等），提供了try with resources方式，在你用完流之后，会给你安全关闭
        try(
                InputStream inputStream =  part.getInputStream();
//                字节流转字符流  + 记得转成UTF-8
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
//                字符流转缓冲流
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        ){
            value = bufferedReader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }
}
